package com.lbc.service.impl;

import com.lbc.bean.dto.NewsDTO;
import com.lbc.bean.entity.News;
import com.lbc.bean.entity.NewsLike;
import com.lbc.bean.vo.NewsVO;
import com.lbc.common.utils.JwtUtils;
import com.lbc.dao.custom.CtNewsLikeMapper;
import com.lbc.dao.custom.CtNewsMapper;
import com.lbc.service.NewsService;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @author xyl
 * @date 2021-03-17 18:32
 */
@Service
public class NewsServiceImpl implements NewsService {

    @Autowired
    private CtNewsMapper newsMapper;
    @Autowired
    private CtNewsLikeMapper newsLikeMapper;

    @Override
    public int add(NewsDTO newsDTO) {
        newsDTO.setNewsId(null);
        News news = new News();
        BeanUtils.copyProperties(newsDTO, news);
        news.setCreateBy(JwtUtils.getUserId());
        news.setCreateTime(new Date());
        news.setPageView(0);
        news.setLikeCount(0);
        return newsMapper.insertSelective(news);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int like(Integer newsId) {
        Integer userId = JwtUtils.getUserId();
        if(userId == -1){
            return 0;
        }
        NewsLike nl = new NewsLike();
        nl.setCreateTime(new Date());
        nl.setLikeBy(userId);
        nl.setNewsId(newsId);
        newsLikeMapper.insert(nl);
        return newsMapper.increaseLikeCount(newsId);
    }

    @Override
    public int pageView(Integer newsId) {
        return newsMapper.increasePageView(newsId);
    }

    @Override
    public List<NewsVO> list(String searchKey) {
        return newsMapper.selectAll(searchKey);
    }

    @Override
    public int modify(NewsDTO newsDTO) {
        News news = new News();
        BeanUtils.copyProperties(newsDTO,news);
        news.setUpdateBy(JwtUtils.getUserId());
        news.setUpdateTime(new Date());
        return newsMapper.updateByPrimaryKeySelective(news);
    }

    @Override
    public int remove(Integer newsId) {
        return newsMapper.deleteByPrimaryKey(newsId);
    }

    @Override
    public NewsVO get(Integer newsId) {
        NewsVO newsVO = new NewsVO();
        News news = newsMapper.selectByPrimaryKey(newsId);
        if(ObjectUtils.isEmpty(news)){
            return null;
        }
        BeanUtils.copyProperties(news,newsVO);
        NewsLike newsLike = newsLikeMapper.selectByNewsIdAndUserId(newsId, JwtUtils.getUserId());
        newsVO.setType(ObjectUtils.isNotEmpty(newsLike));
        return newsVO;
    }

    @Override
    public List<NewsVO> random() {
        return newsMapper.selectRandom();
    }
}
